package com.Long.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/7/23
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
public class mqFanoutTest {

    public static final String EXCAHANG_NAME = "FANOUT_EXCHANAGE";
    public static final String USER_NAME = "admin";
    public static final String PASSWORD = "admin";
    public static final String HOST = "47.101.154.152";
    public static final int PORT = 5672;
    public static final String QUEUW_NAME1 = "queue1";
    public static final String QUEUW_NAME2 = "queue2";
    public static final String ROUTING_KEY1 = "ROUTING_KEY1";
    public static final String ROUTING_KEY2 = "ROUTING_KEY2";


    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST);
        factory.setPort(PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        Connection connection = factory.newConnection();//创建连接
        Channel channel = connection.createChannel();//创建信道；
        channel.confirmSelect();
//创建 fanout 的交换器
        channel.exchangeDeclare(EXCAHANG_NAME, "fanout", true, false, null);
        //创建队列
        channel.queueDeclare(QUEUW_NAME1, true, false, false, null);
        channel.queueDeclare(QUEUW_NAME2, true, false, false, null);

        //将交换器与队列通过路由键进行绑定
        channel.queueBind(QUEUW_NAME1, EXCAHANG_NAME, ROUTING_KEY1);
        channel.queueBind(QUEUW_NAME2, EXCAHANG_NAME, ROUTING_KEY2);

        for (int i = 0; i < 10; i++) {
            String msg = "message num is:" + i;
            channel.basicPublish(EXCAHANG_NAME, i % 2 == 0 ? ROUTING_KEY1 : ROUTING_KEY2, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());

        }
        connection.close();
    }

}
